axios.defaults.baseURL = ' http://ajax-base-api-t.itheima.net'
// 封装一个渲染函数
const form = document.querySelector('#bookForm');
const tn = document.querySelector('#btn');
const renderBooks = () => {
  // 发起请求，请求渲染得数据
  const tb = document.querySelector('#tb');
  axios.get('/api/getbooks').then(({ data: res }) => {
    // console.log(res);
    const { data } = res
 const html =   data.map(item => {
      return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id= '${item.id}'>删除</a></td>
    </tr>`
 }).join('')
    tb.innerHTML = html
  })
}

renderBooks()
tn.addEventListener('click', function () {
  const tb = document.querySelector('#tb');
  axios.get('/api/getbooks').then(({ data: res }) => {
    // console.log(res);
    const { data } = res
 const html =   data.map(item => {
      return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id= '${item.id}'>删除</a></td>
    </tr>`
 }).join('')
    tb.innerHTML = html
  })

})


form.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = serialize(form,{hash:true})
  axios.post('/api/addbook', data)
    .then(({ data: res }) => {
    alert(res.msg)
      if (res.status != 201) return
      this.reset()
      renderBooks()
  })
})
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    let id = e.target.dataset.id
    axios.get('/api/delbook',{params:{id}})
      .then(({ data: res }) => {
        renderBooks()
    })
  }
})